<template>
  <div class="category-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>体验分类</span>
          <el-button type="primary" @click="openDialog()">添加分类</el-button>
        </div>
      </template>

      <!-- 分类列表 -->
      <el-table
        :data="sortedCategories"
        v-loading="loading"
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无分类数据" 
              :image-size="200"
            >
              <div class="empty-text">还没有添加任何体验分类</div>
              <div class="empty-subtext">添加分类对体验项目进行归类管理</div>
              <el-button type="primary" @click="openDialog()" class="mt-4">添加第一个分类</el-button>
            </el-empty>
          </div>
        </template>
        <el-table-column prop="name" label="分类名称" sortable="custom" />
        <el-table-column
          prop="description"
          label="分类描述"
          show-overflow-tooltip
        />
        <el-table-column
          prop="count"
          label="项目数量"
          width="120"
          align="center"
          sortable="custom"
        />
        <el-table-column label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === "active" ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="sort"
          label="排序"
          width="100"
          align="center"
          sortable="custom"
        />
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" size="small" @click="openDialog(row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
                :disabled="row.count > 0"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 添加/编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="formData.id ? '编辑分类' : '添加分类'"
        width="500px"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="分类描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入分类描述"
            />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number
              v-model="formData.sort"
              :min="0"
              :max="999"
              placeholder="数值越小越靠前"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-switch
              v-model="formData.status"
              :active-value="'active'"
              :inactive-value="'inactive'"
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import service from "@/api/axios";

// 表格数据
const categories = ref([]);
const loading = ref(false);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框相关
const dialogVisible = ref(false);
const formRef = ref(null);
const formData = reactive({
  id: "",
  name: "",
  description: "",
  sort: 0,
  status: "active",
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  description: [
    { required: true, message: "请输入分类描述", trigger: "blur" },
    { max: 200, message: "不能超过 200 个字符", trigger: "blur" },
  ],
  sort: [{ required: true, message: "请输入排序值", trigger: "blur" }],
};

// 排序相关
const sortConfig = reactive({
  prop: "",
  order: "",
});

// 获取排序后的数据
const sortedCategories = computed(() => {
  const list = [...categories.value];
  if (!sortConfig.prop) return list;

  return list.sort((a, b) => {
    let aValue = a[sortConfig.prop];
    let bValue = b[sortConfig.prop];

    // 处理数字类型
    if (["count", "sort"].includes(sortConfig.prop)) {
      aValue = Number(aValue);
      bValue = Number(bValue);
    }

    if (sortConfig.order === "ascending") {
      return aValue > bValue ? 1 : -1;
    } else {
      return aValue < bValue ? 1 : -1;
    }
  });
});

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  sortConfig.prop = prop;
  sortConfig.order = order;
};

// 获取分类列表
const fetchData = async () => {
  loading.value = true;
  try {
    // 构建请求参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      sort: sortConfig.prop,
      order: sortConfig.order
    };
    
    const res = await service.get('/admin/experiences/categories', { params });
    
    if (res.code === 200 && res.data) {
      categories.value = res.data.list || [];
      total.value = res.data.total || 0;
    } else {
      // 使用测试数据
      categories.value = [
        {
          id: 1,
          name: "文化体验",
          description: "体验贵港传统文化特色",
          count: 8,
          sort: 1,
          status: "active",
        },
        {
          id: 2,
          name: "手工艺",
          description: "传统手工艺制作体验",
          count: 5,
          sort: 2,
          status: "active",
        },
        {
          id: 3,
          name: "农事体验",
          description: "贵港特色农事活动体验",
          count: 3,
          sort: 3,
          status: "active",
        },
        {
          id: 4,
          name: "美食制作",
          description: "贵港传统美食制作体验",
          count: 6,
          sort: 4,
          status: "active",
        },
      ];
      total.value = 4;
    }
  } catch (error) {
    console.error("获取分类列表失败", error);
    // 使用测试数据
    categories.value = [
      {
        id: 1,
        name: "文化体验",
        description: "体验贵港传统文化特色",
        count: 8,
        sort: 1,
        status: "active",
      },
      {
        id: 2,
        name: "手工艺",
        description: "传统手工艺制作体验",
        count: 5,
        sort: 2,
        status: "active",
      },
      {
        id: 3,
        name: "农事体验",
        description: "贵港特色农事活动体验",
        count: 3,
        sort: 3,
        status: "active",
      },
      {
        id: 4,
        name: "美食制作",
        description: "贵港传统美食制作体验",
        count: 6,
        sort: 4,
        status: "active",
      },
    ];
    total.value = 4;
  } finally {
    loading.value = false;
  }
};

// 打开对话框
const openDialog = (row = null) => {
  if (row) {
    Object.assign(formData, row);
  } else {
    Object.assign(formData, {
      id: "",
      name: "",
      description: "",
      sort: 0,
      status: "active",
    });
  }
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    const isEdit = !!formData.id;
    let res;
    
    if (isEdit) {
      // 编辑
      res = await service.put(`/admin/experiences/categories/${formData.id}`, formData);
    } else {
      // 新增
      res = await service.post('/admin/experiences/categories', formData);
    }
    
    if (res.code === 200) {
      ElMessage.success(formData.id ? "更新成功" : "添加成功");
      dialogVisible.value = false;
      fetchData();
    } else {
      ElMessage.error(res.message || "保存失败");
    }
  } catch (error) {
    console.error("保存失败", error);
    // 表单验证失败或请求失败
    if (error.message) {
      ElMessage.error(error.message);
    }
  }
};

// 删除分类
const handleDelete = (row) => {
  if (row.count > 0) {
    ElMessage.warning("该分类下还有体验项目，无法删除");
    return;
  }

  ElMessageBox.confirm("确定要删除该分类吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      const res = await service.delete(`/admin/experiences/categories/${row.id}`);
      
      if (res.code === 200) {
        ElMessage.success("删除成功");
        fetchData();
      } else {
        ElMessage.error(res.message || "删除失败");
      }
    } catch (error) {
      console.error("删除失败", error);
      ElMessage.error("删除失败");
    }
  });
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.category-management {
  padding: 20px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 40px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-table th) {
  background-color: var(--el-bg-color);
  font-weight: 600;
}

:deep(.el-table__row) {
  transition: background-color 0.3s ease;
}

:deep(.el-table__row:hover) {
  background-color: var(--el-color-primary-light-9) !important;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 12px;
  height: 24px;
  line-height: 24px;
}

:deep(.el-button--small) {
  padding: 6px 12px;
  font-size: 13px;
}

.pagination-container {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid var(--el-border-color-light);
  display: flex;
  justify-content: flex-end;
}

/* 优化对话框样式 */
:deep(.el-dialog) {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: 90vh;
  max-width: 90vw;
}

:deep(.el-dialog__body) {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
}

:deep(.el-dialog__header) {
  padding: 20px;
  margin: 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

:deep(.el-dialog__footer) {
  padding: 20px;
  margin: 0;
  border-top: 1px solid var(--el-border-color-lighter);
}

/* 响应式布局 */
@media (max-width: 768px) {
  .category-management {
    padding: 12px;
  }

  :deep(.el-dialog) {
    width: 90% !important;
  }
}

.empty-state {
  padding: 40px 0;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
